/*
 * @lc app=leetcode.cn id=107 lang=swift
 *
 * [107] 二叉树的层序遍历 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init() { self.val = 0; self.left = nil; self.right = nil; }
 *     public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
 *     public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
 *         self.val = val
 *         self.left = left
 *         self.right = right
 *     }
 * }
 */
class Solution {
    func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
        if root == nil { return [] }

        var res: [[Int]] = []
        var quote: [TreeNode] = []
        quote.append(root!)

        while !quote.isEmpty {
            var list: [Int] = []
            for i in 0..<quote.count {
                let node = quote.removeFirst()

                if node.left != nil {
                    quote.append(node.left!)
                }

                if node.right != nil {
                    quote.append(node.right!)
                }

                list.append(node.val)
            }
            res.insert(list, at: 0)
        }

        return res
    }
}
// @lc code=end

